<?php
// 查询单条记录
function getInfo($table,$where,$field='*'){
    $info = M($table)->where($where)->field($field)->find();
    return $info;
}//end fun getInfo

// 根据u_id查询用户信息
function getMember($u_id,$field='*'){
    $info = M('member')->where('id='.$u_id)->field($field)->find();
    return $info;
}//end fun getMember

// 根据store_id查询店铺名称
function getStore($store_id){
    $info = M('shop_store')->where('id='.$store_id)->getField('storename');
    return $info;
}//end fun getMember

//判断是否点赞
function getIsLike($where){
    $info= M('evaluate_like')->where($where)->find();
    if($info){
        $result = 1;
    }else{
        $result = 0;
    }
    return $result;
}

//积分，余额，卡额变动 $clearingdate为后台给店铺结算了哪天的线下支付收款，例2018-7-2，说明结算了2017-7-2的收款金额
function changeCredit($u_id,$reason,$credit,$ch_type,$num,$shop_credit=0,$clearingdate=''){
    $credit_log = M('member_credit_log');
    $data['u_id'] = $u_id;          //用户u_id
    $data['reason'] = $reason;     //变动原因
    $data['credit_type'] = $credit;  //变动类型
    if($shop_credit==10 || $shop_credit==11 || $shop_credit==12 || $shop_credit==13){
        $data['clearingdate'] = $clearingdate;    //门店余额获取方式
    }
    $data['shop_credit'] = $shop_credit;    //门店余额获取方式
    $data['change_number'] = $num; //变动数量
    $data['change_type'] = $ch_type;       //加减类型
    $data['changetime'] = time();     //变动时间
    $res = $credit_log->add($data);
    return $res;
}

// 推送系统消息
function sendVoice($u_id,$con){
    $data['u_id'] = $u_id;      //用户id
    $data['content'] = $con;    //消息详情
    $data['sendtime'] = time();
    $res = M('voice')->add($data);
    return $res;
}

// 判断主图是否是多图,不是的话直接返回
function isMorePic($img){
    // 判断主图是否有多图
    $is_in = strpos($img, ',');
//        dump($is_in);die;
    if($is_in!=false){
        $img = strstr($img,",",true);
        return $img;
    }else{
        return $img;
    }
}//end fun isMorePic()


// 去除二维数组中的重复元素
function unique_arr($array2D,$stkeep=false,$ndformat=true){
    // 判断是否保留一级数组键 (一级数组键可以为非数字)
    if($stkeep) $stArr = array_keys($array2D);
    // 判断是否保留二级数组键 (所有二级数组键必须相同)
    if($ndformat) $ndArr = array_keys(end($array2D));
    //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
    foreach ($array2D as $v){
        $v = join(",",$v);
        $temp[] = $v;
    }
    //去掉重复的字符串,也就是重复的一维数组
    $temp = array_unique($temp);
    //再将拆开的数组重新组装
    foreach ($temp as $k => $v) {
        if($stkeep) $k = $stArr[$k];
        if($ndformat) {
            $tempArr = explode(",",$v);
            foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
        }
        else $output[$k] = explode(",",$v);
    }
    return $output;
}


// 处理字符串，多余的隐藏
function msubstr($string, $length = 0, $ellipsis = '…', $start = 0) {
    $string = strip_tags($string);
    $string = preg_replace('/\n/is', '', $string);
    //$string=preg_replace('/ |　/is','',$string);//清除字符串中的空格
    $string = preg_replace('/&nbsp;/is', '', $string);
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $string);
    if (is_array($string) && !empty($string[0])) {
        $string = implode('', $string[0]);
        if (strlen($string) < $start + 1) {
            return '';
        }
        preg_match_all("/./su", $string, $ar);
        $string2 = '';
        $tstr = '';
        for ($i = 0; isset($ar[0][$i]); $i++) {
            if (strlen($tstr) < $start) {
                $tstr .= $ar[0][$i];
            } else {
                if (strlen($string2) < $length + strlen($ar[0][$i])) {
                    $string2 .= $ar[0][$i];
                } else {
                    break;
                }
            }
        }
        return $string == $string2 ? $string2 : $string2 . $ellipsis;
    } else {
        $string = '';
    }
    return $string;
}


//根据id获取area
function getarea($id){
    $area = M("area")->where("id = {$id}")->getField('name');
    return $area;
}

//根据id获取category
function getunit($id){
    $category = M("category")->where("id = {$id}")->getField('title');
    return $category;
}
// 给商户推送消息 $u_id member表用户id
function sendMsg($pay_id){
    /*
   $ac = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C('WX_API.appid').'&secret='.C('WX_API.secret'));
   $wxt = json_decode($ac,true);
   $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $wxt['access_token'];//access_token改成你的有效值
   */
    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("access_token.json"));
    if ($data->expire_time < time()) {

        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('WX_API.appid')."&secret=".C('WX_API.secret');
        $access_msg = json_decode(file_get_contents($access_token));
        $access_token = $access_msg->access_token;//获取最新token

        if ($access_token) {
            $data->expire_time = time() + 300;
            $data->access_token = $access_token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $access_token = $data->access_token;
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;//access_token改成你的有效值
    // 根据u_id和查询支付记录
    $pay_info = getInfo('shop_pay_log',array('id'=>$pay_id),'u_id,amount,pay_sn,updated_at,pay_type');
    // 根据支付记录中的u_id获取用户openid
    $openid = getInfo('member',array('id'=>$pay_info['u_id']),'openid');
    $pay_type = $pay_info['pay_type']=='wxpay'?'微信支付':'支付宝支付';
    $pay_time = date('Y-m-d H:i:s',$pay_info['updated_at']);
    $data = array(
        'first' => array(
            'value' => '尊敬的用户您好，您有一笔订单收款成功，请查看。',
            'color' => '#18a689'
        ),
        'keyword1' => array(
            'value' => $pay_info['amount'].'元',
            'color' => '#000'
        ),
        'keyword2' => array(
            'value' => $pay_type,
            'color' => '#000'
        ),
        'keyword3' => array(
            'value' => $pay_time,
            'color' => '#000'
        ),
        'keyword4' => array(
            'value' => $pay_info['pay_sn'],
            'color' => '#000'
        ),
        'remark' => array(
            'value' => '如有问题，请在公众号内留言，我们会及时为您解答。',
            'color' => '#000'
        )
    );
    $template_msg=array('touser'=>$openid['openid'],'template_id'=>'vaQayT5YToKrZUSIZpiVKk5SoddGgzVDJZUeu-l8Vp0','topcolor'=>'#18a689','data'=>$data);
    $curl = curl_init($url);
    $header = array();
    $header[] = 'Content-Type: application/x-www-form-urlencoded';
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    // 不输出header头信息
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 伪装浏览器
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    // 保存到字符串而不是输出
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($curl, CURLOPT_POST, 1);
    // 请求数据
    curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($template_msg));
    $response = curl_exec($curl);
    curl_close($curl);
    //    echo $response;
}//end fun sendMsg

function set_area_js(){
    //该函数生成的字符串为前段地址下拉选择所用
    $area=D('area');
    $getarea_1=$area->where("re_id=0 AND id=408533")->select();//限制湖北区域
    $getarea_2=array();
    $getarea_3=array();
    $altstr="addr_arr[0]=[";
    //循环一级 组成字符串 找出二级
    foreach($getarea_1 as $i=>$one){
        //一级 组成字符串
        $altstr=$altstr.'["'.$one['id'].'","'.$one['name'].'"]';
        if($i+1==count($getarea_1))
        {
            $altstr=$altstr.'],';
        }else{
            $altstr=$altstr.',';
        }
        //找出二级
        $getarea_2[$one['id']]=$area->where("re_id=".$one['id']." AND id=408534")->select();//限制武汉区域
    }//end for
    //循环二级 组成字符串 找出三级
    foreach($getarea_2 as $i=>$one){
        //二级 组成字符串
        $altstr=$altstr."addr_arr[".$i."]=[";
        foreach($one as $k=>$two){
            //二级 组成字符串
            $altstr=$altstr.'["'.$two['id'].'","'.$two['name'].'"]';
            if($k+1==count($one))
            {
                $altstr=$altstr.'],';
            }else{
                $altstr=$altstr.',';
            }
            //找出三级
            $getarea_3[$two['id']]=$area->where("re_id=".$two['id'])->select();
        }//end for
    }//end for
    foreach($getarea_3 as $i=>$one){
        //三级 组成字符串
        $altstr=$altstr."addr_arr[".$i."]=[";
        foreach($one as $k=>$two){
            //三级 组成字符串
            $altstr=$altstr.'["'.$two['id'].'","'.$two['name'].'"]';
            if($k+1==count($one))
            {
                $altstr=$altstr.'];';
            }else{
                $altstr=$altstr.',';
            }
        }//end for
    }//end for
    //dump($getarea_2);
    return $altstr;
}//end fun
